﻿#pragma once

#include <utility>

/**
 * 对COM接口指针进行包装，以便自动Release
 */
template <typename T>
class com_interface
{
public:
    com_interface() noexcept
        : ptr(nullptr)
    {}

    com_interface(com_interface&& other) noexcept
        : ptr(other.ptr)
    {
        other.ptr = nullptr;
    }

    ~com_interface()
    {
        release();
    }

    com_interface& operator=(com_interface&& other) noexcept
    {
        if (this != &other)
        {
            release();
            ptr = other.ptr;
            other.ptr = nullptr;
        }
        return *this;
    }

    com_interface(const com_interface&) = delete;
    com_interface& operator=(const com_interface&) = delete;

    /**
     * @brief 返回一个可修改的COM接口指针的地址
     *
     * @return 指针地址
     */
    T** address() noexcept
    {
        return &ptr;
    }

    T* operator->() const noexcept
    {
        return ptr;
    }

    T* get() const noexcept
    {
        return ptr;
    }

private:
    void release()
    {
        if (ptr != nullptr)
        {
            ptr->Release();
        }
    }

private:
    T* ptr;
};
